import uuid
import pathlib

import aiofiles
from fastapi import APIRouter, UploadFile, File

from app.models import responses
from app.services import files, accounts
from app.config import STATIC_IMG_FOLDER

router = APIRouter(
    prefix='/api/v1/files',
    tags=['backend', 'files']
)


@router.post('/upload/image')
async def upload_image(_account: accounts.LoggedInAccount, file: UploadFile = File()):
    if not file.content_type.startswith("image/"):
        return responses.Response102(msg='仅允许图片文件')

    image_id = uuid.uuid4()
    image_suffix = pathlib.Path(file.filename).suffix
    filename = f'{image_id}{image_suffix}'
    filepath = STATIC_IMG_FOLDER / filename

    async with aiofiles.open(filepath, 'wb') as buffer:
        await buffer.write(await file.read())

    thumb_stem = await files.generate_thumb(filepath)

    return responses.SuccessResponse(data={
        'url': f'/images/{filename}',
        'thumb': f'/images/{thumb_stem}{image_suffix}',
        'alt': filename,
        'href': ''
    })
